from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from meiduo import settings


def generate_access_token(openid):
    """
    签名openid
    :param openid:   用户的id
    :return: access_token
    """

    serializer = Serializer(settings.SECRET_KEY, 600)
    data = {'openid': openid}
    token = serializer.dumps(data)
    return token.decode()


def check_access_token(access_token):
    """
    提取openid
    :param access_token: 签名后的openid
    :return:
    """
    serializer = Serializer(settings.SECRET_KEY, 600)
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get("openid")


# if __name__ == '__main__':
#     g_token = generate_access_token('123')
#     print(g_token)
#     c_token = check_access_token(g_token)
#     print(c_token)